const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const model = require('../db/model');
const moment = require('moment');


passport.use(new LocalStrategy(
    (username, password, done) => {
      model.user.findOne({
        where: {
          user_name: username,
        },
      }).then((item) => {
        const user = item?item.dataValues:false;
        if (!user) {
          return done(null, false);
        }
        if (password !== user.pwd) {
          return done(null, false);
        }
        model.user.update({
          login_time: moment().format('YYYY-MM-DD HH:mm:ss'),
        },
          {
            where: {
              id: user.id,
            },
          });
        return done(null, user);
      }).catch(err => done(err));
    }
));
passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((userid, done) => {
  model.user.findOne({
    where: {
      id: userid,
    },
  }).then((ress) => {
    done(null, ress);
  }).catch(err => done(err));
});
module.exports = passport;